package com.smn.jsf;

import com.smn.domain.MyUser;
import com.smn.jsf.util.JsfUtil;
import com.smn.jsf.util.PaginationHelper;
import com.smn.dao.MyUserFacade;
import java.io.Serializable;
import java.util.Date;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

@ManagedBean(name = "myUserController")
@SessionScoped
public class MyUserController implements Serializable {

    private MyUser current;
    private DataModel items = null;
    @EJB
    private com.smn.dao.MyUserFacade myUserFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    @PersistenceContext
    EntityManager em;

    public MyUserController() {
    }

    public void setCurrentUser(MyUser user) {
        this.current = user;
    }

    public MyUser getCurrent() {
        return current;
    }

    public String login() {
        MyUser myuser = myUserFacade.findUser(current.getUserName());
        if (myuser != null) {//check password
            if (myuser.getPassword().equals(current.getPassword())) {
                setCurrentUser(myuser);
                return "MenuBanner";
            } else {
                JsfUtil.addErrorMessage("Username or Password is wrong");
            }
        } else {
            String names[] = current.getFirstName().split(" ");
            String firstName = "";
            String lastName = "";
            if (names.length >= 2) {
                for (int i = 0; i < names.length - 1; i++) {
                    firstName += names[i] + " ";
                }
                lastName = names[names.length - 1];
            } else if (names.length == 1) {
                firstName = names[0];
            }
            current.setFirstName(firstName);
            current.setLastName(lastName);
            current.setDateCreated(new Date());
            myUserFacade.create(current);
            return "MenuBanner";
        }
        return "welcome";
    }

    public MyUser getSelected() {
        if (current == null) {
            current = new MyUser();
            selectedItemIndex = -1;
        }
        return current;
    }

    private MyUserFacade getFacade() {
        return myUserFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (MyUser) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new MyUser();
        selectedItemIndex = -1;
        return null;
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MyUserCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (MyUser) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MyUserUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (MyUser) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("MyUserDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(myUserFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(myUserFacade.findAll(), true);


    }

    @FacesConverter(forClass = MyUser.class)
    public static class MyUserControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            MyUserController controller = (MyUserController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "myUserController");
            return controller.myUserFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof MyUser) {
                MyUser o = (MyUser) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + MyUserController.class.getName());
            }
        }
    }
}
